<!--
  -   房产管理.   :permission="permissionList"
  - Author: lengleng (wangiegie@gmail.com)
  -->
<template>
  <div class="execution">
    <basic-container>
      <avue-crud
        ref="crud"
        :page="page"
        :data="tableData"
        :table-loading="tableLoading"
        :option="tableOption"
        :search.sync="searchForm"
        @search-change="searchChange"
        @refresh-change="refreshChange"
        @size-change="sizeChange"
        @current-change="currentChange"
        @row-del="handleDelete"
        @search-reset="SearchReset"
      >
        <template
          slot="projectFloorNumberSearch"
        >
       
          <el-input
            v-model="searchForm.projectFloorNumber"
            style="width:100%;"
            placeholder='请输入楼层'
            @input.native="searchForm.projectFloorNumber = test(searchForm.projectFloorNumber)"
          ></el-input>
        </template>
        <template
          slot="projectAreaSearch"
        >
        
          <el-input
            v-model="searchForm.projectArea"
            style="width:100%;"
            placeholder='请输入面积'
            @input.native="searchForm.projectArea = test1(searchForm.projectArea)"
          ></el-input>
        </template>
        <template
          slot="projectTypeId"
          slot-scope="scope"
        >
          {{scope.row.projectTypeId | GetTypeName(scope.row.buildingType,that)}}
        </template>
        <template
          slot="menuLeft"
        >
          <el-button
            v-if="estate_rmproject_add"
            class="filter-item"
            type="primary"
            icon="el-icon-plus"
            @click="addOrUpdateHandle('add','')"
          >
            新增
          </el-button>
          <el-button
            v-if="estate_rmproject_export"
            class="filter-item"
            type="default"
            icon="el-icon-download"
            @click="rmEexport()"
          >
            导出
          </el-button>
          <el-button
            v-if="estate_rmproject_import"
            class="filter-item"
            type="default"
            icon="el-icon-upload2"
            @click="rmImport()"
          >
            导入
          </el-button>
        </template>

        <template
          slot="projectNumber"
          slot-scope="scope"
        >
          <el-link
            type="primary"
            :underline="false"
            @click="handleView('view',scope.row.id)"
          >{{scope.row.projectNumber}}</el-link>
        </template>
        <template
          slot="modifyContractId"
          slot-scope="scope"
        >
          <el-link
            type="primary"
            :underline="false"
            @click="handleContractView('view',scope.row.ctContract.contractNumber,scope.row.id)"
          >{{scope.row.ctContract==null?'':scope.row.ctContract.contractNumber}}</el-link>
        </template>

        <template
          slot="menu"
          slot-scope="scope"
        >
          <el-button
            v-if="estate_rmproject_get"
            type="text"
            @click="handleView('view',scope.row.id)"
          >
            查看
          </el-button>
          <!-- <el-button
            v-if="estate_rmproject_edit && scope.row.projectStatus!=1 && scope.row.projectStatus!=3"
            type="text"
            @click="addOrUpdateHandle('edit',scope.row.id)"
          >
            编辑
          </el-button> -->
          <el-button
            v-if="estate_rmproject_del"
            type="text"
            @click="handleDelete(scope.row,scope.index)"
          >
            删除
          </el-button>
        </template>
      </avue-crud>

      <table-form
        v-if="addOrUpdateVisible"
        ref="addOrUpdate"
        @refreshDataList="getList"
      ></table-form>
      <table-forms
        v-if="viewVisible"
        ref="viewBtn"
        @refreshDataList="getList"
      ></table-forms>
      <CtContractModifys
        v-if="viewConVisible"
        ref="viewContract"
      ></CtContractModifys>

    </basic-container>
    <!--导入-->
    <el-dialog
      title="批量导入"
      :visible.sync="uploadlg.show"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      width="400px"
      :before-close="BeforeClose"
    >
      下载模板：<el-button
        type="text"
        size="mini"
        style="color:#409EFF;"
        @click="onDowmload"
      >房产导入模板.xlsx</el-button>

      <br>
      <br>
      <el-upload
        ref="upload"
        class="upload-box"
        drag
        action=""
        :http-request="HttpRequest"
        :auto-upload="false"
        multiple
        :limit="1"
        :on-exceed="handleExceed"
        name="files"
        :before-upload="beforeUpload"
        :data="uploadlg.extraData"
        :on-change="changeUpload"
        :on-remove="reMoveUpload"
        :on-success="uploadSuccess"
      >
        <i class="el-icon-upload" />
        <div class="el-upload__text">将文件拖到此处，或<em>点击选择导入文件</em></div>
      </el-upload>
      <span
        slot="footer"
        class="dialog-footer"
      >
        <el-button
          type="primary"
          size="mini"
          icon="el-icon-upload2"
          @click="submitFile"
        >导入</el-button>
      </span>
    </el-dialog>
  </div>
</template>
<script src="https://cdnjs.cloudflare.com/ajax/libs/FileSaver.js/1.3.8/FileSaver.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.14.1/xlsx.full.min.js"></script>
<script>
import { fetchList, getObj, addObj, putObj, delObj, getProjectpProperty, getProjectStatus, ImportFile } from '@/api/market/estate/rmproject'
import { tableOption } from '@/const/crud/market/estate/rmproject'
import TableForm from './RmProjectForm'
import TableForms from './RmProjectModify'
import CtContractModifys from './contract'
import { mapGetters } from 'vuex'
import { getDicType, ExportUrlFile, ExportFile } from '@/api/common'
export default {
  name: 'rmproject',
  components: { TableForm, TableForms, CtContractModifys },
  data () {
    return {
      addOrUpdateVisible: false,
      viewVisible: false,
      viewConVisible: false,
      tableLoading: true,
      searchForm: {
        projectFloorNumber: '',
        projectArea: ''
      },
      tableData: [],
      that: this,
      page: {
        total: 0, // 总页数
        currentPage: 1, // 当前页数
        pageSize: 20 // 每页显示多少条
      },
      uploadlg: {
        show: false,
        noUploadFile: true
      },
      proBuildTypeList: [],
      proStatusList: [],
      projectPropertyList: [],
      tableOption: tableOption,
      estate_rmproject_get: false,
      estate_rmproject_add: false,
      estate_rmproject_edit: false,
      estate_rmproject_del: false,
      estate_rmproject_import: false,
      estate_rmproject_export: false,
      zhlList: [],
      zcList: [],
      xxdList: [],
      search: {},
      Lists: {}
    }
  },
  created () {
    this.estate_rmproject_get = this.permissions['estate_rmproject_get']
    this.estate_rmproject_add = this.permissions['estate_rmproject_add']
    this.estate_rmproject_edit = this.permissions['estate_rmproject_edit']
    this.estate_rmproject_del = this.permissions['estate_rmproject_del']
    this.estate_rmproject_export = this.permissions['estate_rmproject_export']
    this.estate_rmproject_import = this.permissions['estate_rmproject_import']

    //房产状态
    getProjectStatus().then(response => {
      if (response.data != null) {
        this.proStatusList = response.data.data;
      }
       console.log(this.proStatusList,'房产状态');
    })

    //房产性质
    getProjectpProperty().then(response => {
      if (response.data != null) {
        this.projectPropertyList = response.data.data;
      }
     
    })

    //获取房产类型
    // getProjectType().then(response => {
    //   if (response.data != null) {
    //     this.proBuildTypeList = response.data.data;
    //   }
    // })
  },
  filters: {
    GetTypeName (value, value1, that) {
      let str = value
      // if (value1 == 2) {
      //   that.zhlList.forEach(item => {
      //     if (value == item.value) {
      //       str = item.label
      //     }
      //   })
      // } else if (value1 == 3) {
      //   that.zcList.forEach(item => {
      //     if (value == item.value) {
      //       str = item.label
      //     }
      //   })
      // } else if (value1 == 1) {
      //   that.xxdList.forEach(item => {
      //     if (value == item.value) {
      //       str = item.label
      //     }
      //   })
      // }
      // that.Lists[value1].forEach(item => {
      //   if (value == item.value) {
      //     str = item.label
      //   }
      // })
      return str
    }
  },
  mounted () {
    getDicType("rm_project_buiding_type").then(res => {
      let resData = res.data.data
      resData.forEach((item) => {
        getDicType(item.value).then(res => {
          this.Lists[item.value] = res.data.data
        })
      })
    })
    this.getList(this.page)
  },
  computed: {
    ...mapGetters(['elements', 'permissions'])
  },
  methods: {
    test (value) {
      if (value.indexOf('-') === 0) {
        return '-' + value.replace(/[^\d+]/g, '')
      } else {
        return value.replace(/[^\d+]/g, '')
      }
    },
    test1 (value) {
      value = value.replace(/[^\d.]/g, '').replace(/\.{2,}/g, '.').replace('.', '$#$').replace(/\./g, '').replace('$#$', '.').replace(/^(-)*(\d+)\.(\d\d).*$/, '$1$2.$3').replace(/^\./g, '')
      return value
    },
    BeforeClose () {
      this.uploadlg.show = false
      this.$refs.upload.clearFiles()
    },
    getList (page, params) {
      this.tableLoading = true
      if (this.searchForm.projectFloorNumber && this.searchForm.projectFloorNumber != '-') {
        this.searchForm.projectFloorNumber = parseInt(this.searchForm.projectFloorNumber)
      }
      fetchList(Object.assign({
        current: this.page.currentPage,
        size: this.page.pageSize
      }, params, this.searchForm)).then(response => {
        this.tableData = response.data.data.records;
        console.log(this.tableData,'获取房产列表');
        this.page.total = response.data.data.total;
        this.tableLoading = false;
      }).catch(() => {
        this.tableLoading = false
      })
    },
    // 删除
    handleDelete: function (row, index) {
      if (row.projectStatus == 1 || row.projectStatus == 3) {
        this.$message.warning('房产已租/已售,不允许删除！')
        return;
      }
      this.$confirm('是否确认删除此条数据？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(function () {
        return delObj(row.id)
      }).then(data => {
        this.$message.success('删除成功！')
        this.getList(this.page)
      })
    },
    //合同查看
    handleContractView: function (method, projectNumber, id) {
      this.viewConVisible = true
      this.$nextTick(() => {
        this.$refs.viewContract.init(method, projectNumber, id)
      })
    },
    // 查看
    handleView: function (method, id) {
      this.$router.push({
        path: '/houselist', query:{id:id}

        });
     /*  this.viewVisible = true */
      this.$nextTick(() => {
        this.$refs.viewBtn.init(method, id)
      })
    },
    // 新增、修改
    addOrUpdateHandle (isEdit, id) {
      this.$router.push('/add')
     // publicPath:'add'
    //  this.addOrUpdateVisible = true
    //   this.$nextTick(() => {
    //     this.$refs.addOrUpdate.init(isEdit, id)
    //   })
    },
    // 导出
    rmEexport: function () {
      if (this.searchForm.projectFloorNumber) {
        this.search.projectFloorNumber = this.searchForm.projectFloorNumber
      }
      if (this.searchForm.projectArea) {
        this.search.projectArea = this.searchForm.projectArea
      }
      ExportFile('/estate/rmproject/export', Object.assign({}, this.search, this.searchForm))
    },
    // 导入
    rmImport: function () {
      this.uploadlg.show = true;
    },
    sizeChange (pageSize) {
      this.page.pageSize = pageSize
      this.getList(this.page)
    },
    currentChange (current) {
      this.page.currentPage = current
      this.getList(this.page)
    },
    searchChange (form, done) {
      this.search = form
      this.page.currentPage = 1
      this.getList(this.page, form)
      done()
    },
    refreshChange () {
      this.getList(this.page)
    },
    beforeUpload (file) {
      const isExcel = file.type === 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet' || file
        .type === 'application/vnd.ms-excel'
      if (!isExcel) {
        this.$message.warning('导入文件格式只能上传.xlsx或.xls!')
      }

      const isLt50M = file.size / 1024 / 1024 < 50
      if (!isLt50M) {
        this.$message.warning('上传文件的大小不能超过 50M!')
      }

      return isLt50M && isExcel
    },
    handleExceed (files) {
      this.$message.warning(`当前导入限制只能上传 1 个文件`)
    },
    uploadSuccess (response) {
      const reSuccess = response.success
      if (reSuccess === 0) {
        if (response.data === null) {
          this.$message({
            type: 'error',
            message: response.msg
          })
        } else {
          this.$message({
            type: 'error',
            message: response.data.map(item => {
              return item.failMsg + '|'
            }).join()
          })
        }
        this.$refs.upload && this.$refs.upload.clearFiles()
        return
      }

      this.uploadlg.show = false
      this.$message({
        type: 'success',
        message: '上传成功!'
      })
      this.$refs.upload.clearFiles()
      this.$refs.listTable.initTableData()
    },
    changeUpload (file, fileList) {
      if (fileList.length > 0) {
        this.uploadlg.noUploadFile = false
      } else {
        this.uploadlg.noUploadFile = true
      }
    },
    reMoveUpload (file, fileList) {
      if (fileList.length === 0) {
        this.uploadlg.noUploadFile = true
      }
    },
    // 覆盖action方法，自定义上传方法
    HttpRequest (file) {
      let fromdata = new FormData()
      fromdata.append("file", file.file)
      ImportFile(fromdata).then(res => {
        if (res.data.code == 0) {
          this.BeforeClose()
          this.$message({
            type: 'success',
            message: '导入成功!'
          })
          this.$refs.upload.clearFiles()
          this.getList(this.page)
        } else {
          this.$message({
            type: 'error',
            message: '导入失败!'
          })
        }
      })
    },
    submitFile () {
      if (this.uploadlg.noUploadFile) {
        this.$message({
          type: 'warning',
          message: '请选择文件'
        })

        return
      }
      this.$refs.upload.submit()
    },
    onDowmload () {
      ExportUrlFile('/contract/template/1', {})
    },
    SearchReset () {
      this.searchForm = {
        projectFloorNumber: '',
        projectArea: ''
      }
    }
  }
}
</script>
